package com.kum.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.kum.domain.AjaxResult;
import com.kum.domain.constant.UserType;
import com.kum.domain.entity.*;
import com.kum.mapper.SysUserMapper;
import com.kum.service.SysUserPlayRecordService;
import com.kum.service.SysUserService;
import com.kum.service.security.LoginUser;
import com.kum.utils.CryptoUtils;
import com.kum.utils.IpUtils;
import com.kum.utils.RequestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @version V1.0
 * @Package com.kum.controller
 * @auhter 枯木Kum
 * @date 2021/3/3-4:36 PM
 */

@RestController
@RequestMapping("/system/user")
public  class SysUserController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserPlayRecordService sysUserPlayRecordService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 用户列表
     * @return
     */
    @GetMapping("/list")
//    @PreAuthorize("@ps.hasPermi('system:user:list')")
    public AjaxResult list() {
        return AjaxResult.success(sysUserService.list());
    }
//    @PreAuthorize("@ps.hasPermi('system:user_admin:list')")
    @GetMapping("/admin/list")
    public AjaxResult listOfAdmin() {
        return AjaxResult.success(sysUserService.findByUserRole(UserType.ADMIN));
    }

    @PostMapping("/register")
    public AjaxResult register(@RequestBody SysUser sysUser, HttpServletRequest req) {
        if (StringUtils.isEmpty(sysUser.getPassword())) {
            sysUser.setPassword("123456");
        }
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(new Date());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userId", sysUserService.register(sysUser, false));
        return AjaxResult.success(jsonObject);
    }

    @PostMapping("/save")
    public AjaxResult save(@RequestBody SysUser sysUser, HttpServletRequest req) throws Exception {
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(new Date());
        // 解密密码
        if (StringUtils.isNotEmpty(sysUser.getPassword())) {
            sysUser.setPassword(CryptoUtils.decryptByRSA(CryptoUtils.privKey, sysUser.getPassword()));
        }
        if(sysUser.getId() == null){
//            if(sysUser.getPassword() == null){
//                sysUser.setPassword("123456");
//            }
            sysUserService.register(sysUser, true);
        }else{
            sysUserService.save(sysUser);
        }
        return AjaxResult.success();
    }

    @GetMapping("/isAdmin")
    public AjaxResult role() {
        boolean isAdmin = false;
        try {
            LoginUser loginUser = RequestUtils.getCurrentLoginUser();
            isAdmin = sysUserService.isAdmin(loginUser.getUser().getId());
        } catch (Exception e) {
            RequestUtils.Forbidden();
        }
        return AjaxResult.success(isAdmin);
    }

    /**
     * 业主信息列表
     */
    @GetMapping("/household/list")
//    @PreAuthorize("@ps.hasPermi('system:user_householdInfo:list')")
    public AjaxResult HouseholdInfoList() {
        return AjaxResult.success(sysUserService.HouseholdInfoList());
    }

    /**
     * 业主信息的增加或更新
     *
     * @param sysUserInfoData
     */
    @PostMapping("/household/save")
//    @PreAuthorize("@ps.hasPermi('system:user_householdInfo:save')")
    public AjaxResult HouseholdInfoSave(@RequestBody SysUserInfoData sysUserInfoData) {
        sysUserService.HouseholdInfoSave(sysUserInfoData);
        return AjaxResult.success();
    }

    @PostMapping("/household/delete")
//    @PreAuthorize("@ps.hasPermi('system:user_householdInfo:delete')")
    public AjaxResult HouseholdInfoDelete(@RequestBody SysUserInfo sysUserInfo) {
        sysUserService.HouseholdInfoDelete(sysUserInfo);
        return AjaxResult.success();
    }

    @GetMapping("/pay/record/month")
    public AjaxResult getPayRecordOfMonth(){
        LoginUser user = RequestUtils.getCurrentLoginUser();
        return AjaxResult.success(sysUserPlayRecordService.findByOfMonth(user.getUser().getId()));
    }
    @GetMapping("/pay/fess/{chargeTypeId}")
    public AjaxResult paymentFees(@PathVariable("chargeTypeId") Integer chargeTypeId){
        LoginUser user = RequestUtils.getCurrentLoginUser();
        sysUserPlayRecordService.paymentFees(user.getUser().getId(),chargeTypeId);
        return AjaxResult.success();
    }

    @PostMapping("/household/updatePassWord")
//    @PreAuthorize("@ps.hasPermi('system:user_householdInfo:delete')")
    public AjaxResult updatePassWord(@RequestBody PassWordUpdate passWordUpdate) throws Exception {
        // 前端加密的字符解密
        passWordUpdate.setNewPassword(CryptoUtils.decryptByRSA(CryptoUtils.privKey, passWordUpdate.getNewPassword()));
        passWordUpdate.setOldPassword(CryptoUtils.decryptByRSA(CryptoUtils.privKey, passWordUpdate.getOldPassword()));
        // 根据用户名查查询用户信息
        LoginUser loginUser = RequestUtils.getCurrentLoginUser();
        // 对比用户信息密码是否正确
        boolean matches = passwordEncoder.matches(passWordUpdate.getOldPassword(), loginUser.getUser().getPassword());
        if (!matches) {
           AjaxResult.error("输入原密码不正确");
        }
        // 执行更改
//        LambdaUpdateWrapper<SysUser> updateWrapper = new LambdaUpdateWrapper<SysUser>();
//        LambdaUpdateWrapper<SysUser> eq = updateWrapper.set(SysUser::getPassword, )
//                .eq(SysUser::getId, loginUser.getUser().getId());
        SysUser sysUser = new SysUser();
        sysUser.setPassword(passwordEncoder.encode(passWordUpdate.getNewPassword()));
        sysUser.setId(loginUser.getUser().getId());
        sysUserMapper.updateById(sysUser);
        return AjaxResult.success();
    }
}
